package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.EsManagerService;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private SearchService searchService;

    @Autowired
    private EsManagerService esManagerService;

    //对搜索入参带有特殊符号进行处理
    public void handlerSearchMap(Map<String, String> searchMap) {

        if (null != searchMap) {
            Set<Map.Entry<String, String>> entries = searchMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                if (entry.getKey().startsWith("spec_")) {
                    searchMap.put(entry.getKey(), entry.getValue().replace("+", "%2B"));
                }
            }
        }

    }

    /**
     * 全文检索
     */
    @GetMapping("/list")
    public String search(@RequestParam Map<String, String> searchMap, Model model) {
        //特殊符号处理
        handlerSearchMap(searchMap);
        Map<String, Object> resultMap = searchService.search(searchMap);
        model.addAttribute("result", resultMap);
        model.addAttribute("searchMap", searchMap);

        //分页
        com.changgou.entity.Page<SkuInfo> page = new Page<SkuInfo>(
                Long.parseLong(resultMap.get("totalPages").toString()),      //总记录数
                Integer.parseInt(resultMap.get("pageNum").toString()),       //当前页
                Page.pageSize                                                //每页显示的条数
        );
        model.addAttribute("page", page);

        //拼装url
        StringBuilder url = new StringBuilder("/search/list");
        if (searchMap != null && searchMap.size() > 0) {
            url.append("?");
            for (String key : searchMap.keySet()) {
                if (!"sortRule".equals(key) && !"sortField".equals(key) && !"pageNum".equals(key)) {
                    url.append(key).append("=").append(searchMap.get(key)).append("&");
                }
            }
            String urlString = url.toString();
            urlString = urlString.substring(0, urlString.length() - 1);
            model.addAttribute("url", urlString);
        } else {
            model.addAttribute("url", url);
        }
        return "search";
    }
}
